const app = getApp()
const db = wx.cloud.database()
Page({
  data: {
    orderinfo: [],
    totalprice: 0
  },

  onLoad: function (options) {
    var orderinfo = JSON.parse(options.orderinfo)
    var totalprice = 0
    for (var i = 0; i < orderinfo.length; i++) {
      totalprice = totalprice + orderinfo[i].saleprice * orderinfo[i].num
    }
    totalprice = parseInt(totalprice * 100) / 100
    totalprice = totalprice.toFixed(2)
    this.setData({
      orderinfo: orderinfo,
      totalprice: totalprice
    })
  },

  onClickButton: function (event) {
    var orderinfo = this.data.orderinfo
    var totalprice = this.data.totalprice
    var userInfo = wx.getStorageSync('userInfo');
    db.collection('order').add({
        data: {
          orderinfo: orderinfo,
          totalprice: totalprice,
          submitorder: db.serverDate(),
          _openid: userInfo._openid
        }
      })
      .then(res => {
        var sum = app.globalData.goodnum
        let promiseArr = [];
        for (let i = 0; i < orderinfo.length; i++) {
          let promise = new Promise((resolve, reject) => {
            db.collection('shoppingcart').doc(orderinfo[i]._id).remove({
              success: function(res) {
                sum = sum - orderinfo[i].num
                resolve('sucesss')
              }
            })
          })
          promiseArr.push(promise)
        }
        Promise.all(promiseArr).then((result) => {
          wx.showToast({
            title: '订单提交成功...',
            icon: 'none',
            duration: 1500
          })
          console.log("order")
          wx.switchTab({
            url: '../home/home'
          })
        })
      })
      .catch(console.error)
  }

})